package com.smag.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.smag.common.core.domain.AjaxResult;
import com.smag.common.core.domain.entity.FarmTech;
import com.smag.common.core.redis.RedisCache;
import com.smag.common.enums.AppHttpCodeEnum;
import com.smag.common.exception.base.BaseException;
import com.smag.common.utils.StringUtils;
import com.smag.common.utils.http.HttpUtils;
import com.smag.system.domain.vo.FarmIdentify;
import com.smag.system.mapper.FarmTechMapper;
import com.smag.system.service.FarmTechService;
import com.sun.imageio.plugins.common.ImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
* @author hzqhzq
* @description 针对表【farm_crop】的数据库操作Service实现
* @createDate 2023-03-26 14:14:05
*/
@Slf4j
@Service
public class FarmTechServiceImpl extends ServiceImpl<FarmTechMapper, FarmTech>
        implements FarmTechService {
    @Resource
    private FarmTechMapper farmTechMapper;

    @Resource
    private RedisCache redisCache;

    static final HttpUtils HTTP_CLIENT = new HttpUtils();
    static final String CLIENT_ID = "zosZEDDbMuttJerwR3P3CcM3";
    static final String CLIENT_SECRET = "libUfR4InX8S3bVS0gu3z29V3iEgwrpB";

    @Override
    public List<FarmTech> pageListCrop(FarmTech farmTech,Long userId) {
        LambdaQueryWrapper<FarmTech> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId),FarmTech::getCreateBy,userId);
        queryWrapper.like(StringUtils.isNotEmpty(farmTech.getCropName()),FarmTech::getCropName,farmTech.getCropName());
        List<FarmTech> list = list(queryWrapper);
        return list;
    }

    @Override
    public AjaxResult deleteCropByIds(Long[] cropIds) {
        if (!removeByIds(Arrays.asList(cropIds))) {
             throw new BaseException(AppHttpCodeEnum.SYSTEM_ERROR.getMsg());
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult updateCrop(FarmTech farmTech) {
        String oldCropName = getById(farmTech.getCropId()).getCropName();
        if (!oldCropName.equals(farmTech.getCropName())){
            if (!checkCropNameUnique(farmTech.getCropName())) {
                return AjaxResult.error("修改农作物'" + farmTech.getCropName() + "'失败，农作物名称已存在");
            }
        }
        if (!updateById(farmTech)) {
            throw new RuntimeException("修改失败");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult insertCrop(FarmTech farmTech) {
        if (!checkCropNameUnique(farmTech.getCropName())) {
            return AjaxResult.error("添加农作物'" + farmTech.getCropName() + "'失败，农作物名称已存在");
        }
        if (!save(farmTech)) {
            throw new RuntimeException("添加失败");
        }
        return AjaxResult.success();
    }

    @Override
    public Boolean updateTechAvatar(Long cropId, String avatar) {
        if (farmTechMapper.updateTechAvatar(cropId,avatar) > 0)
            return true;
        return false;

    }

    @Override
    public FarmIdentify identify(MultipartFile file) {
        FarmIdentify farmIdentify = new FarmIdentify();

        //先查找redis中有没有access_token
        String userId = redisCache.getCacheObject("sys_config:sys.user.initRoleId");
        String key = "Cache_ACCESS_TOKEN" + userId;

        String ACCESS_TOKEN = redisCache.getCacheObject(key);

//        if (StringUtils.isEmpty(ACCESS_TOKEN)){
//            log.info("获取access_token");
//            String map = "grant_type=client_credentials&client_id=" + CLIENT_ID + "&client_secret=" + CLIENT_SECRET;
//            String url = "https://aip.baidubce.com/oauth/2.0/token?client_id=&client_secret=&grant_type=client_credentials";
//            ACCESS_TOKEN = HTTP_CLIENT.sendPost(url, map);
//            ACCESS_TOKEN = ACCESS_TOKEN.substring(ACCESS_TOKEN.indexOf("access_token") + 15, ACCESS_TOKEN.indexOf("scope") - 3);
//
//            redisCache.setCacheObject(key, ACCESS_TOKEN, 2591000, TimeUnit.SECONDS);
//        }


        ACCESS_TOKEN = "24.89a495e87c30af330651183aa01a27d1.2592000.1715769220.282335-61523552";
        String url2 = "https://aip.baidubce.com/rest/2.0/image-classify/v1/plant" + "?access_token=" + ACCESS_TOKEN;

        try {
            String result = HTTP_CLIENT.sendPost2(url2, multipartFileToBase64(file), ACCESS_TOKEN);
            // 创建一个ObjectMapper对象
            ObjectMapper mapper = new ObjectMapper();

            // 使用readValue方法将JSON字符串转换为FarmIdentify对象
            farmIdentify = mapper.readValue(result, FarmIdentify.class);

            log.info("识别结果：{}", farmIdentify);

        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return farmIdentify;
    }

    /**
     * MultipartFile转base64
     * @param file
     * @return
     */
    public static String multipartFileToBase64(MultipartFile file) {
        byte[] fileBytes = new byte[0];
        try {
            fileBytes = file.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String base64String = Base64.getEncoder().encodeToString(fileBytes);

//        System.out.println(base64String);

        return base64String;
    }

    private boolean checkCropNameUnique(String cropName){
        LambdaQueryWrapper<FarmTech> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(cropName),FarmTech::getCropName,cropName);
        if (getOne(queryWrapper) != null) {
            return false;
        }
        return true;
    }
}




